package com.pig4cloud.pigx.contract.executer.trade.handler;

import com.pig4cloud.pigx.common.customize.exception.MqAckException;
import com.pig4cloud.pigx.common.customize.mysql.utils.MysqlUtil;
import com.pig4cloud.pigx.common.customize.utils.CommonUtil;
import com.pig4cloud.pigx.common.seata.utils.SeataUtils;
import com.pig4cloud.pigx.contract.bo.ContractTradeHandleBO;
import com.pig4cloud.pigx.contract.constant.OrderExecutorErrorMsg;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 成交记录处理器管理器
 *
 * @since 2022/8/17 11:12
 */
@Data
@Slf4j
@Component
public class TradeHandlerManager {
	/**
	 * 成交记录处理器集合
	 */
	private final List<TradeHandler> handlerList = new ArrayList<>();
	/**
	 * 成交记录处理器集合
	 */
	@Autowired
	private CommonUtil commonUtil;
	@Autowired
	private MysqlUtil mysqlUtil;

	/**
	 * 成交记录处理
	 *
	 * @param tradeId 成交记录id
	 * @since 2022/8/17 11:15
	 */
	public void handle(Long tradeId) {
		ContractTradeHandleBO bo = new ContractTradeHandleBO();

		// long time1 = System.currentTimeMillis();
		for (TradeHandler i : handlerList) {
			try {
				if (Objects.isNull(bo.getMongo())) {
					bo.setMongo(i.getTrade(tradeId));
				}

				if (!i.support(bo.getMongo())) {
					continue;
				}

				i.handle(bo);
				i.success(bo);
				// System.err.println("成交记录处理耗时：" + (System.currentTimeMillis() - time1));
				return;
			} catch (Exception e) {
				// 回滚钱包模块分布式事务
				SeataUtils.rollbackGlobalTx();
				// 回滚本地事务
				mysqlUtil.rollbackLocalTx();

				i.fail(bo, e);

				// System.err.println("成交记录处理耗时：" + (System.currentTimeMillis() - time1));
				if (e instanceof MqAckException) {
					return;
				}

				log.error(OrderExecutorErrorMsg.TRADE_NEW_ERROR, e.getMessage());
				throw e;
			}
		}

		throw new RuntimeException(OrderExecutorErrorMsg.TRADE_HANDLE_NOT_MATCH);
	}
}
